const util = require('../../../../utils/util.js')
const App = getApp()
Page({
  /**
   * 页面的初始数据
   */
  data: {
    apiUrl: util.apiUrl,
    selected: 1,
    detailList: {},
    tuilist: ['赠品', '人气搭配'],
    color: 'black',
    id: null,
    animationData: {},
    isSelect: ['standardNormal', 'standardSelected', 'standardDisable'],
    /* 用于区别当前的规格是否选中 */
    commodityStandard: [],
    standardInfo: [],
    selectedId: [],
    selectedStandard: [],
    standardObject: {},
    commodityNum: 1,
    navStyle: [],
    shoucang: 0,
    goods_id: 0,
    is_integral: 0,
    appraisesList: [], //评价
    empty_image: '', // 空状态图标
    isEmpty: 'load',
    shopCartConut: 0,
    chanDiKuangImage: util.Background_base64('static/image/goods/chandikuang.png'),
    navigation: { type: 'fraction' }
  },
  // 跳转溯源页面
  openSy() {
    wx.navigateTo({
      url: ''
    })
  },
  // 切换
  selected: function (e) {
    let that = this
    let index = e.currentTarget.dataset.index
    that.setData({
      selected: index
    })
    this.getData()
  },
  //返回上一页
  navigateBack: function () {
    util.navigateBack()
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    // 转化本地图片地址为base64格式
    this.setData({
      empty_image: util.Background_base64('static/image/goods/wujieguo.png')
    })
    this.setData({
      id: options,
      navStyle: App.globalData,
      is_integral: options.is_integra
    })
  },
  //获取商品详情
  async getdetail(options) {
    let ret = await util.request('/api/goods/details', options)
    var datas = ret.data
    if (datas.code == 0) {
      this.setData({
        detailList: datas.data,
        commodityStandard: datas.data.specs,
        standardInfo: datas.data.list,
        goods_id: options.id,
        isEmpty: 'success'
      })
      let commodit = datas.data.specs
      // 默认规格选中
      let event_my = {
        currentTarget: {
          dataset: {
            id: datas.data.specs[0].list[0].name,
            standardIndex: 0,
            index: 0
          }
        }
      }
      this.setData({
        detailList: datas.data,
        commodityStandard: datas.data.specs,
        standardInfo: datas.data.list,
        goods_id: options.id,
        isEmpty: 'success'
      })
      this.handleStandardClick(event_my)
      console.log(this.data.detailList, 'this.data.detailList')
    } else {
      wx.showToast({
        title: datas.msg,
        icon: 'none'
      })
      this.setData({
        isEmpty: 'error'
      })
    }
    let newarr = []
    newarr = this.data.detailList
    newarr.checked = false //定义是否被选中,为购物车铺路
    //判断商品是否被收藏
    if (newarr.coll_id > 0) {
      var shoucang = 1
      var coll_id = newarr.coll_id
    } else {
      var shoucang = 0
      var coll_id = 0
    }
    //获取 评价内容
    util.request('/api/goods/goodsAppraises', options, 'GET').then((res) => {
      let datasAp = res.data.data
      var newArr = []
      if (datas.code == 0) {
        if (datasAp.list.length > 0) {
          datasAp.list.forEach((val) => {
            val.score = parseInt(val.score)
          })
          this.setData({
            appraisesList: datasAp.list
          })
        }
      } else {
        wx.showToast({
          title: datas.msg,
          icon: 'none'
        })
      }
    })
    this.setData({
      detailList: newarr,
      shoucang: shoucang,
      coll_id: coll_id
    })
    this.getProductConut()
  },
  /* 规格选择 */
  standardSelect(e) {
    var types = e.currentTarget.dataset.types
    this.setData({
      visible: true,
      types: types,
      is_integral: e.currentTarget.dataset.is_integral
    })
  },
  onVisibleChange(e) {
    this.setData({
      visible: e.detail.visible
    })
  },
  /* 每个规格的点击事件 */
  handleStandardClick(e) {
    let id = e.currentTarget.dataset.id
    // 总规格名称索引
    let standardIndex = e.currentTarget.dataset.standardIndex
    // 单个规格名称索引
    let index = e.currentTarget.dataset.index
    let commodityStandard = this.data.commodityStandard
    let standardLength = commodityStandard[standardIndex].list.length
    let standardSku = commodityStandard[standardIndex].name
    // 用于存储规格的id
    let selectedId = this.data.selectedId
    // 用总规格名称索引来存储每个选中的规格id
    selectedId[standardIndex] = standardSku + '::' + id
    let selectedStandard = this.data.selectedStandard
    // 在点击的时候，只需要对点击的这个规格所在的数组进行循环
    for (let i = 0; i < standardLength; i++) {
      // 找到对应的单个规格索引，并设置check及单个规格名称
      if (index == i) {
        commodityStandard[standardIndex].list[index].check = false
        selectedStandard[standardIndex] = commodityStandard[standardIndex].list[index].name
      } else {
        commodityStandard[standardIndex].list[i].check = true
      }
      console.log(commodityStandard[standardIndex])
    }

    // 将id用_连接起来
    let mergeId = selectedId.join(';;')
    let mergeStandard = selectedStandard.join('  ')
    console.log(mergeStandard)
    let standardInfo = this.data.standardInfo
    let standardInfoLength = standardInfo.length
    // 用于存储选中的规格
    let standardObject = {}
    for (let i = 0; i < standardInfoLength; i++) {
      if (standardInfo[i].goods_spec == mergeId) {
        standardObject = standardInfo[i]
        console.log(standardObject)
        break
      } else {
        standardObject = this.data.standardObject
      }
    }
    console.log(standardObject.number_stock)
    this.setData({
      currentId: id,
      commodityStandard,
      selectedId,
      standardObject,
      mergeStandard,
      selectedStandard,
      number_stock: standardObject.number_stock
    })
  },
  /* 选择数量 */
  handleCommodityNumber(e) {
    console.log(e)
    let commodityNum = e.detail.value
    if (commodityNum >= this.data.number_stock) {
      commodityNum = this.data.number_stock
    }
    console.log(commodityNum)
    this.setData({
      commodityNum
    })
  },
  /* 保存选择的规格 */
  submitSelected(e) {
    let selectedStandard = this.data.selectedStandard
    let length = selectedStandard.length
    if (length == 0) {
      wx.showToast({
        title: '请选择规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
      return false
    } else {
      for (let i = 0; i < length; i++) {
        if (length < this.data.commodityStandard.length) {
          wx.showToast({
            title: '请选择规格',
            icon: 'error',
            duration: 1000 //持续的时间
          })
          break
        }
        if (selectedStandard[i] == undefined) {
          wx.showToast({
            title: '请选择规格',
            icon: 'error',
            duration: 1000 //持续的时间
          })
          break
        }
      }
      // wx.showToast({
      //     title: '选择成功',
      //     type: 'success',
      //     duration: 1000//持续的时间
      // });
      // 调取加入购物车
      if (this.data.types == 1) {
        this.addcart()
      } else {
        this.over()
      }
    }
  },
  addcart() {
    if (util.isLogin() !== true) {
      return false
    }
    let token = wx.getStorageSync('token')
    //请求头参数
    const header = {
      Authorization: token
    }
    var params = {
      token: token,
      goods_id: this.data.standardObject.goods_id,
      list_id: this.data.standardObject.id,
      goods_number: this.data.commodityNum
    }
    if (params.goods_id == '' || params.goods_id == undefined) {
      wx.showToast({
        title: '请选择完整商品规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    } else if (params.list_id == '' || params.list_id == undefined) {
      wx.showToast({
        title: '请选择商品规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    } else {
      util.request('/api/cart/addcart', params, 'POST').then((res) => {
        console.log(res)
        if (res.data.code == 0) {
          this.setData({
            visible: false
          })
          util.showtoast(
            {
              msg: res.data.msg,
              icon: 'none'
            },
            1000
          )
          this.getProductConut()
        } else {
          util.showtoast(
            {
              msg: res.data.msg,
              icon: 'none'
            },
            1000
          )
        }
      })
    }
  },
  /*图片预览 */
  preview(e) {
    let src = e.currentTarget.dataset.src
    let bigsrc = this.data.detailList.pics.map((item) => {
      return item.pics_big_url
    })
    wx.previewImage({
      current: src, //原图片路径
      urls: bigsrc //图片放大路径
    })
  },
  //购买
  over(e) {
    if (util.isLogin() !== true) {
      return false
    }
    var params = {
      goods_id: this.data.standardObject.goods_id,
      list_id: this.data.standardObject.id,
      goods_number: this.data.commodityNum,
      is_integral: this.data.is_integral
    }
    if (params.goods_id == '' || params.goods_id == undefined) {
      wx.showToast({
        title: '请选择完整商品规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    } else if (params.list_id == '' || params.list_id == undefined) {
      wx.showToast({
        title: '请选择商品规格',
        icon: 'error',
        duration: 1000 //持续的时间
      })
    } else {
      util.request('/api/cart/buyNow', params, 'POST').then((res) => {
        if (res.data.code == 0) {
          wx.showToast({
            title: '添加成功跳转订单页',
            icon: 'success',
            duration: 1000 //持续的时间
          })
          var urlPay = '/pages/confirmcart/confirmcart?cartIds=' + res.data.data.cart_id
          wx.navigateTo({
            url: urlPay
          })
        } else {
          wx.showToast({
            title: '添加失败',
            icon: 'error',
            duration: 1000 //持续的时间
          })
        }
      })
    }
  },
  // 跳转溯源
  gtSuyuan(e) {
    wx.navigateTo({
      url: '/modules/goodsModule/pages/goodssyuan/goodssyuan?gid=' + e.currentTarget.dataset.g_id
    })
  },
  // 获取购物车商品数量
  getProductConut() {
    util.request('/api/cart/index', {}, 'GET').then((response) => {
      const res = response.data
      if (res.code === 0 && res.data.cart_list !== 0) {
        const newList = res.data.cart_list
        let allNum = 0
        for (var i = 0; i < newList.length; i++) {
          if (newList[i].select === 1) {
            allNum += parseInt(newList[i].goods_number)
          }
        }

        this.setData({
          shopCartConut: allNum
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.getdetail(this.data.id)
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {},

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {},

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {
    return {
      title: this.data.detailList.title,
      imageUrl: this.data.detailList.image[0]
    }
  }
})
